<%@ page language="java" pageEncoding="UTF-8"%>
<script>
 
var debug = false;


(function($) { 
	    $.fn.getAllData = function() {
	    	var data = {};
	    	this.find('input').each(function(){
	    			data[$(this).attr('name')] = $(this).val();
	    	});
	    	this.find('select').each(function(){
	    			data[$(this).attr('name')] = $(this).val();
	    	});
	    	return data;
	    };
})(jQuery);
 
function getQueryStringByDecode(name) { 
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return decodeURI(r[2]); return "";
} 

 function getInputHtml(col,crudDefaultInputWidth){

	 var html = "";
	 var width = "";
	 var height = null;
	 var clickHtml = "";
	 var display = "";
	 if(crudDefaultInputWidth==null){
		 width = '';
	 }else{
		 width = 'width:'+crudDefaultInputWidth+";";
	 }
	 if(col.input==null){
	     col.input = {};
	     col.input.type = "text";
     }
     if(col.update==false&&col.insert==false){
         col.input.type = "hidden";
     }

     if(col.click!=null){
         clickHtml = ' onclick= " '+col.click+' "; ';
     }

     if(col.input.type=="password" || col.input.type=="text" || col.input.type =="hidden"){
         html += '<input  data-defaultvalue="'+col.defaultValue+'" '+clickHtml+' id="crud-'+col.field+'"  style=" '+width+' " name="'+col.field+'" data-insert='+col.insert+'  data-update='+col.update+' value="" data-type="'+col.type+'"    >';
     }
     if(col.input.type == 'textarea'){
			 	if(col.input.height!=null){
			 		height = col.input.height+"px"; 
			 	}else{
			 		height = "100px";
			 	}
				html += '<textarea id="crud-'+col.field+'" '+clickHtml+'  style="width:'+crudDefaultInputWidth+';height: '+height+' ;" name="'+col.field+'" data-insert='+col.insert+'  data-update='+col.update+' value="" data-type="'+col.type+'"    ></textarea>';
     }
     if(col.input.type == 'radio'){
				var values = col.input.value;
				for(var ii = 0 ; ii<values.length; ii++){
					var isDefault = values[ii].isDefault;
					var isDefaultHtml = ' ';
					if(isDefault!=null && isDefault){
						isDefault = true;
						isDefaultHtml = ' checked' ;
					}else{
						isDefault = false;
					}
					html += (values[ii].text + '<input id="crud-'+col.field+'"  '+clickHtml+'  data-value="'+values[ii].value+'" data-insert='+col.insert+'  data-update='+col.update+'   data-isDefault="'+isDefault+'" '+isDefaultHtml+'  name="'+col.field+'" type="radio" style="margin-right: 15px;"    >');
				}
				if(col.formatter==null){
					col.formatter = function(value,row){
					    var html = "";
						for(var a = 0;a< values.length;a++){
							if(value==values[a].value){
                                html =  values[a].text;
                                break;
							}
						}
                        rowFormatterFinal(row,col,html);
						return html;
					}
				}
      }
	 return html;
 }
 
 function initCrudDialog(column,dom){
	 	 
	 	if(dom==null){
	 		dom = 'crudDialog';
	 	}
		$('#'+dom+' input').each(function(){
			var $this = $(this);
			var type = $this.data('type');
			var col = column.contains('field',$this.attr('name')).data;
			 
			$this.on("keydown", function (e) {
		        if (e.keyCode == 13) {
		        	var nextOk = false;
		        	var i = 0;
		        	var next = $this.parent().next();
		        	while(!nextOk){
		        		if(next.length==0){
			        		nextOk = true;
			        		$('#saveBtn').click();
			        	}else{
			        		nextOk = (next.css('display')=='block' && !next.find('input').prop('readonly') );
			        	}
		        		if(nextOk){
		        			next.find('input').focus();
		        			next.find('input').click();
		        		}
		        		next = next.next();
		        	}
		        }
		    });
			
			if(col.dialog!=null){
				dialogHandler($this,col,dom);
				return;
			}
			 
			if(type == 'img'){
				imgHandler($this,col);
			}
            if(type == 'imgs'){
                imgsHandler($this,col);
            }
			if(type == 'date'){
				dateHandler($this,col);
			}
			if(type == 'number'){
				numberHandler($this,col);
			}
		});
}
function rowFormatterFinal(row,col,value) {
    row["formatter-"+col.field] = value;
}
 function dialogHandler($this,col,dom){


        if(col.dialog.combobox!=null){
            if(col.dialog.data == null){
                postAsyncFalse(col.dialog.url,{},function (res) {
                    col.dialog.data = res.data;
                });
            }
                $this.combobox({
                    valueField:col.dialog.combobox.valueField,
                    textField:col.dialog.combobox.textField,
                    data:col.dialog.data
                });
                col.formatter = function (value,row) {
                    var html = "";
                    $.each(col.dialog.data,function (index,row) {
                        if(row[col.dialog.combobox.valueField] == value){
                            html = row[col.dialog.combobox.textField];
                        }
                    });

                    rowFormatterFinal(row,col,html);
                    return  html;
                };
                return;
        }



        //默认弹窗
	 	var id = dom+'-'+col.title;
		$this.click(function(){
            if(col.update!=null&&col.update==false){
		        return;
            }
            if(col.insert!=null&&col.insert==false){
                return;
            }
            if(col.dialog.width==null){
                col.dialog.width='380px'
            }
            if(col.height==null){
                col.dialog.height='90%'
            }
            layer.open({
                type: 2,
                title: col.title,
                shadeClose: true,
                shade: 0.8,
                area: [col.dialog.width, col.dialog.height],
                content: col.dialog.url, //iframe的url
                btn:['确定'],
                yes: function (index, layero) {
                    var bool = col.dialog.select($(layero).find("iframe")[0].contentWindow);
                    if(bool==null ||bool == true){
                        layer.close(index);
                    }

                },
            });
		});
 }
 function imgsHandler($this,cb){
     $this.click(function(){
         var html = "";
         var urls = $this.val().split(",");
         var id = new Date().getTime();
         html += '<ul class="imgs" id="'+id+'">'
         if($this.val().trim()!=""){
             for(var i =0 ;i<urls.length;i++){
                 html += '<li><img src="'+urls[i]+'" style="width: 80px;height: 80px;margin: 3px"/><button>X</button></li>';
             }
         }

         html += "</ul>";

         layer.open({
             type: 1,
             skin: 'layui-layer-rim', //加上边框
             area: ['90%', '90%'], //宽高
             title:"图片管理",
             content: html,
             btn:['上传','确定'],
             yes: function (index, layero) {

                 editor.loadPlugin('image', function() {
                     editor.plugin.imageDialog({
                         showRemote : false,
                         clickFn : function(url, title, width, height, border, align) {
                             $('#'+id).append('<li><img src="'+url+'" style="width: 80px;height: 80px;margin: 3px"/><button>X</button></li>');
                             initImgs(id);
                             editor.hideDialog();
                         }
                     });
                 });
             },
             btn2:function () {
                 var map = [];
                 $('#'+id+ " li").each(function () {
                     var $li = $(this);
                     var top = parseInt($li.css('top').split("px")[0]);
                     var left = parseInt($li.css('left').split("px")[0]);
                     map.push({index: (top*10000)+left,src:$li.find('img').attr('src')});
                 });
                 map = map.sorted("index","asc")
                 var urls = "";
                 for(var i =0 ;i<map.length;i++){
                     urls += map[i].src ;
                     if(i<map.length-1){
                         urls += ',';
                     }
                 }
                 $this.val(urls);
                 if(cb!=null){
                     cb(urls);
                 }
                 return true;
             }
         });
         initImgs(id);
    });
 }
 function imgHandler($this){
	   $this.parent().append('<button type="button" >清空</button>');
       $this.parent().find('button').click(function () {
            $(this).parent().find('input').val('');
       });
	   $this.change(function(){
			$this.parent().find('img').attr('src',$this.val());
			$this.parent().find('img').click(function(){
				window.top.showPic($(this).attr('src'));
			})
		});

     $this.click(function(){
         editor.loadPlugin('image', function() {
             editor.plugin.imageDialog({
                 showRemote : false,
                 clickFn : function(url, title, width, height, border, align) {
                     $this.val(url);
                     $this.change();
                     editor.hideDialog();
                 }
             });
         });
     });
};
 function dateHandler($this,col){
     layui.use('laydate', function() {
         if(col.dateType==null){
             col.dateType = 'datetime';
         }
         layui.laydate.render({
             elem: "#"+$this.attr('id')
             ,trigger: 'click'
             ,type: col.dateType
         });
     });
 }
 function numberHandler($this){
	 $this.keyup(function(){  
         var c=$(this);
         c.val(c.val().replace(/[^0-9.]/g,''));
     });   
 }
 
 
 function bindOrGetData(row,dom){
		var result = {};
		var bind = false;
		if(row){
			bind = true;
		}
		if(dom==null){
			dom = 'crudDialog';
		}


		
		$('#'+dom+ ' input,#'+dom+' textarea').each(function(){
		    var $this = $(this);
			var name = $this.attr('name');
			var value = $this.val();
			var update = $this.data('update');
            var col ;
                col = colMap[name];



			if(bind){
                if(col!=null){

                    if(col.dialog!=null){
                        if(col.dialog.combobox!=null){
                            $(this).val(row[name]);
                            $('#crud-'+name).combobox('select', row[name]);
                        }
                    }else{
                        if($(this).attr('type')=='radio'){
                            $(this).parent().find("input[type='radio']").each(function(){
                                if($(this).data('value')==row[name]){
                                    $(this).prop('checked',true);
                                }
                            });
                        }else{
                            $(this).val(row[name]);
                        }
                        $(this).change();
                    }
                }


				 if(!update){
                     $('#crud-'+name+'-div').hide();
					 //$(this).attr('readonly',true);//$(this).attr('disabled',true);
				 }else{
				     if(col.hidden==null || col.hidden==false){
                         $('#crud-'+name+'-div').show();
                     }//$(this).attr('readonly',false);
				 }
			}else{
				if($(this).attr('type')=='radio'){
					result[name] = $(this).parent().find("input[type='radio']:checked").data('value');
					return;
				}
				result[name] = value;			
			}
		});
		return result;
}
 
 
 
 
 Array.prototype.sorted = function(field,direct){
		var result = this;
		result = result.sort(
	            function(a, b)
	            {
	            	var aValue = a[field];
	            	var bValue = b[field]; 
	            	if(direct==null ||direct=="asc"){
	            		if(aValue < bValue) {
	                    	return -1;
	                    }
	                    if(aValue > bValue){
	                    	return 1;
	                    }
	            	}
	            	if(direct=="desc"){
	            		if(aValue < bValue) {
	                    	return 1;
	                    }
	                    if(aValue > bValue){
	                    	return -1;
	                    }
	            	}
	                return 0;
	            }
		);
		return result;
	};
	Array.prototype.contains = function(field,value){
		var find = false;
		var data = null;
		for(var i =0 ;i<this.length;i++){
			var row = this[i];
			for(key in row){
				if(field==key&&row[key]==value){
					find = true;
					data = row;
				}
			}
			if(find){
				break;
			}
		}
		return {find :find,data:data};
	};
	
	function createViewFrame(param){
		$('body').append('<div id="body"  style="width:'+$(window).width()+'px;height:'+$(window).height()+'px"></div>')
		
		printStructHtml(param.struct,"body");
	}
	function printStructHtml(struct,domId){
		var $this = $('#'+domId);
		for(var i =0 ;i<struct.length;i++){
			var row = struct[i];
			var h = row.h;
			var id = row.id;
			var newId = domId+"-"+i;
			$this.append('<div id="'+newId+'"  style="height:'+h+';width:99%" ></div>');
			var $newthis = $('#'+newId);
			if(h== null || h==""){
				var height = $newthis.parent().height();
				$newthis.siblings().each(function(){
					height -= ($(this).height()+10);
				});
				$newthis.height(height);
			}
			for(var j = 0;j<row.w.length;j++){
				var m = row.w[j];
				var newSubId = newId+"-"+j
				
				var content = ""; 
				if(m.frame!=null){
					content = getIframeHtml(m.frame);
				}
				if(m.html != null){
					content = m.html ;
				}
				var debugHtml = "";
				if(debug){
					debugHtml = "border:1px solid #CCC;"
				}
				$newthis.append('<div id="'+newSubId+'"  style="width:'+m.w+';height:99%;float: left;'+debugHtml+'">'+content+'</div>');
				if(m.w==null || m.w == ""){
					var $newSub  = $('#'+newSubId);
					var width = $newSub.parent().width();
					$newSub.siblings().each(function(){
						width -= ($(this).width()+10);
					});
					$('#'+newSubId).width(width);
				}
				if(m.struct!=null){
					printStructHtml(m.struct,newSubId);
				}
				 
			}
		}
	}
	
	function getIframeHtml (frame){
		return '<div style="width:99%;height:99%"><iframe id="'+frame.id+'" name="centerIframe" src="${base}'+frame.src+'" style="background-color: white;" frameborder="no" width="100%"  height="100%" allowtransparency="true" border="0"></iframe></div>';
	}

	function clearForm(){
		$('#crudDialog input').each(function(){
			var insert = $(this).data('insert');
            var name = $(this).attr('name');
            var col = colMap[name];
            if(insert != null && insert==false){
                $('#crud-'+name+'-div').hide();
                $(this).unbind();
                //$(this).attr('readonly',true);//$(this).attr('disabled',true);
            }else{
                if(col!=null && (col.hidden==null || col.hidden==false)){
                    $('#crud-'+name+'-div').show();
                }//$(this).attr('readonly',false);
            }
            /*
			if(insert != null && insert==false){
				$(this).attr('readonly',true);
                $(this).attr('disabled',true);
                $(this).unbind();
			}else{
				$(this).attr('readonly',false);
			}*/
			var type = $(this).attr('type');
			if(type=="text"){
				$(this).val('');
			}else if(type=="radio"){
				$(this).prop('checked',$(this).data('isdefault'));
			}else if(col!=null && col.dialog!=null){
			    if(col.dialog.combobox!=null){
                    $("#crud-"+name).combobox('clear')
                }
            }else{
                $(this).val('');
            }
			
			var defaultValue = $(this).data('defaultvalue');
			if(defaultValue!="undefined"){
				$(this).val(defaultValue);
			}
		});
	}


function initImgs(id) {

    var oUl= document.getElementById(id);
    var aLi = oUl.getElementsByTagName("li");
    var disX = 0;
    var disY = 0;
    var minZindex = 1;
    var aPos =[];
    for(var i=0;i<aLi.length;i++){
        $(aLi[i]).find('button').click(function () {
            $(this).parent().detach();//.detach();
            setTimeout(function () {
                initImgs(id);
            },1000);
        });
        $(aLi[i]).attr("style","");
        var t = aLi[i].offsetTop;
        var l = aLi[i].offsetLeft;
        aLi[i].style.top = t+"px";
        aLi[i].style.left = l+"px";
        aPos[i] = {left:l,top:t};
        aLi[i].index = i;
    }
    for(var i=0;i<aLi.length;i++){
        aLi[i].style.position = "absolute";
        aLi[i].style.margin = 0;
        setDrag(aLi[i]);
    }
    //拖拽
    function setDrag(obj){
        obj.onmouseover = function(){
            obj.style.cursor = "move";
        }
        obj.onmousedown = function(event){
            var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
            var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft;
            obj.style.zIndex = minZindex++;
            //当鼠标按下时计算鼠标与拖拽对象的距离
            disX = event.clientX +scrollLeft-obj.offsetLeft;
            disY = event.clientY +scrollTop-obj.offsetTop;
            document.onmousemove=function(event){
                //当鼠标拖动时计算div的位置
                var l = event.clientX -disX +scrollLeft;
                var t = event.clientY -disY + scrollTop;
                obj.style.left = l + "px";
                obj.style.top = t + "px";
                /*for(var i=0;i<aLi.length;i++){
                 aLi[i].className = "";
                 if(obj==aLi[i])continue;//如果是自己则跳过自己不加红色虚线
                 if(colTest(obj,aLi[i])){
                 aLi[i].className = "active";
                 }
                 }*/
                for(var i=0;i<aLi.length;i++){
                    aLi[i].className = "";
                }
                var oNear = findMin(obj);
                if(oNear){
                    oNear.className = "active";
                }
            }
            document.onmouseup = function(){
                document.onmousemove = null;//当鼠标弹起时移出移动事件
                document.onmouseup = null;//移出up事件，清空内存
                //检测是否普碰上，在交换位置
                var oNear = findMin(obj);
                if(oNear){
                    oNear.className = "";
                    oNear.style.zIndex = minZindex++;
                    obj.style.zIndex = minZindex++;
                    startMove(oNear,aPos[obj.index]);
                    startMove(obj,aPos[oNear.index]);
                    //交换index
                    oNear.index += obj.index;
                    obj.index = oNear.index - obj.index;
                    oNear.index = oNear.index - obj.index;
                }else{

                    startMove(obj,aPos[obj.index]);
                }
            }
            clearInterval(obj.timer);
            return false;//低版本出现禁止符号
        }
    }
    //碰撞检测
    function colTest(obj1,obj2){
        var t1 = obj1.offsetTop;
        var r1 = obj1.offsetWidth+obj1.offsetLeft;
        var b1 = obj1.offsetHeight+obj1.offsetTop;
        var l1 = obj1.offsetLeft;

        var t2 = obj2.offsetTop;
        var r2 = obj2.offsetWidth+obj2.offsetLeft;
        var b2 = obj2.offsetHeight+obj2.offsetTop;
        var l2 = obj2.offsetLeft;

        if(t1>b2||r1<l2||b1<t2||l1>r2){
            return false;
        }else{
            return true;
        }
    }
    //勾股定理求距离
    function getDis(obj1,obj2){
        var a = obj1.offsetLeft-obj2.offsetLeft;
        var b = obj1.offsetTop-obj2.offsetTop;
        return Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
    }
    //找到距离最近的
    function findMin(obj){
        var minDis = 999999999;
        var minIndex = -1;
        for(var i=0;i<aLi.length;i++){
            if(obj==aLi[i])continue;
            if(colTest(obj,aLi[i])){
                var dis = getDis(obj,aLi[i]);
                if(dis<minDis){
                    minDis = dis;
                    minIndex = i;
                }
            }
        }
        if(minIndex==-1){
            return null;
        }else{
            return aLi[minIndex];
        }
    }
    ;
//閫氳繃class鑾峰彇鍏冪礌
    function getClass(cls){
        var ret = [];
        var els = document.getElementsByTagName("*");
        for (var i = 0; i < els.length; i++){
            //鍒ゆ柇els[i]涓槸鍚﹀瓨鍦╟ls杩欎釜className;.indexOf("cls")鍒ゆ柇cls瀛樺湪鐨勪笅鏍囷紝濡傛灉涓嬫爣>=0鍒欏瓨鍦�;
            if(els[i].className === cls || els[i].className.indexOf("cls")>=0 || els[i].className.indexOf(" cls")>=0 || els[i].className.indexOf(" cls ")>0){
                ret.push(els[i]);
            }
        }
        return ret;
    }
    function getStyle(obj,attr){//瑙ｅ喅JS鍏煎闂鑾峰彇姝ｇ‘鐨勫睘鎬у€�
        return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,false)[attr];
    }
    function startMove(obj,json,fun){
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var isStop = true;
            for(var attr in json){
                var iCur = 0;
                //鍒ゆ柇杩愬姩鐨勬槸涓嶆槸閫忔槑搴﹀€�
                if(attr=="opacity"){
                    iCur = parseInt(parseFloat(getStyle(obj,attr))*100);
                }else{
                    iCur = parseInt(getStyle(obj,attr));
                }
                var ispeed = (json[attr]-iCur)/8;
                //杩愬姩閫熷害濡傛灉澶т簬0鍒欏悜涓嬪彇鏁达紝濡傛灉灏忎簬0鎯充笂鍙栨暣锛�
                ispeed = ispeed>0?Math.ceil(ispeed):Math.floor(ispeed);
                //鍒ゆ柇鎵€鏈夎繍鍔ㄦ槸鍚﹀叏閮ㄥ畬鎴�
                if(iCur!=json[attr]){
                    isStop = false;
                }
                //杩愬姩寮€濮�
                if(attr=="opacity"){
                    obj.style.filter = "alpha:(opacity:"+(json[attr]+ispeed)+")";
                    obj.style.opacity = (json[attr]+ispeed)/100;
                }else{
                    obj.style[attr] = iCur+ispeed+"px";
                }
            }
            //鍒ゆ柇鏄惁鍏ㄩ儴瀹屾垚
            if(isStop){
                clearInterval(obj.timer);
                if(fun){
                    fun();
                }
            }
        },30);
    }

}
</script>
<style>
    .imgs {width:90%; position:relative; }
    .imgs li {width:100px; height:100px; float:left; list-style:none; }
    .imgs li:hover{ border-color: #9a9fa4; box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.85);}
    .imgs .active{ border:1px dashed red;}

</style>